package com.sys.basics.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sys.basics.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @author: ares
 * @date: 2021/9/26 20:40
 * @description: 自动填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now());
        try {
            Long userId = ShiroUtils.getUserId();
            this.strictUpdateFill(metaObject, "creatorId", Long.class, userId);
            this.strictUpdateFill(metaObject, "modifierId", Long.class, userId);
        } catch (Exception e) {
            log.error("自动填充[插入操作]-->获取userId失败");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now());
        try {
            Long userId = ShiroUtils.getUserId();
            this.strictUpdateFill(metaObject, "modifierId", Long.class, userId);
        } catch (Exception e) {
            log.error("自动填充[更新操作]-->获取userId失败");
        }
    }
}
